package com.itboye.core.utils;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.util.Log;

import com.google.gson.Gson;
import com.itboye.core.object.SpPublicParams;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.data.model.AvatarBeans;
import com.itboye.mengwu.data.model.Data;
import com.itboye.mengwu.data.model.RootBean;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class ImageCompressAndUpload {

	private static final MediaType MEDIA_TYPE_PNG = MediaType
			.parse("image/png");
	private ExecutorService executorService;
	private static ImageCompressAndUpload upload;

	// private OnUploadlistener uploadListener;

	private ImageCompressAndUpload() {
		executorService = Executors.newFixedThreadPool(4);
	}

	/**
	 * 单例
	 * 
	 * @return
	 */
	public static synchronized ImageCompressAndUpload getInstance() {
		if (upload == null) {
			upload = new ImageCompressAndUpload();
		}

		return upload;
	}

	public  synchronized void execute(final String path,
			final OnUploadlistener uploadListener, final String type) {
		executorService.execute(new Runnable() {

			@Override
			public synchronized void run() {

				Handler handler = new Handler(Looper.getMainLooper()) {
					@Override
					public synchronized void handleMessage(android.os.Message msg) {
						switch (msg.what) {
						case 0:
							Data resultData = (Data) msg.getData()
									.getSerializable("result");

							// requestCode =
							// msg.getData().getInt("requestCode");
							System.out.println("图片路径" + uploadListener + ":::"
									+ resultData + "::" + resultData.getImage());
							DebugLog.v("imageUpload", "-->Success\n",
									"localPath:", path, "\nurl:", resultData);
							uploadListener
									.OnSuccess(resultData.getImage() == null ? resultData
											.getId() : resultData.getImage()
											.getId());

							break;
						case 1:
							String errorInfo = "上传失败";
							DebugLog.v("imageUpload", "-->Error\n",
									"localPath:", path, "\n", msg.obj);
							uploadListener.OnError(errorInfo);

							break;
						default:
							break;
						}

					}
				};

				try {
					File file = new File(ImageCompress.compress(path));

					OkHttpClient client = new OkHttpClient();
					client.setConnectTimeout(10, TimeUnit.SECONDS);
					client.setReadTimeout(15, TimeUnit.SECONDS);
					client.setWriteTimeout(30, TimeUnit.SECONDS);

					// 创建请求BODY
					RequestBody requestBody = new MultipartBuilder()
							.type(MultipartBuilder.FORM)
							.addFormDataPart(
									"uid",
									(String) SPUtils.get(
											MainApplication.context, null,
											SpPublicParams.UID, ""))
							.addFormDataPart("type", type)
							.addFormDataPart("image", file.getName(),
									RequestBody.create(MEDIA_TYPE_PNG, file))
							.build();

					Request request = new Request.Builder()
							.url("http://api.moodwo.com/public/index"
									+ ".php/file/upload?access_token=ACCESS_TOKEN&client_id=by565fa4facdb191")
							.post(requestBody).build();

					Response response = client.newCall(request).execute();
					if (!response.isSuccessful()) {
						Message msg = handler.obtainMessage();
						msg.what = 1;
						msg.obj = "请求失败";
						handler.sendMessage(msg);
					} else {

						String result = response.body().string();
						// if(code==0)
						// JSONObject jsonObject = new JSONObject(result);
						// String resultData = jsonObject.getString("data");

						DebugLog.v("bytag", result);
						Gson gson = new Gson();
						RootBean avatarBeans = gson.fromJson(result,
								RootBean.class);// 获取到网络端数据,多个参数
						if (avatarBeans.getCode() == 0) {
							Message msg = new Message();
							msg.what = 0;
							Bundle bundle = new Bundle();
							bundle.putSerializable("result",
									avatarBeans.getData());
							msg.setData(bundle);
							handler.sendMessage(msg);

						} else {
							Message msg = handler.obtainMessage();
							msg.what = 1;
							msg.obj = "code！=0 " + result;
							handler.sendMessage(msg);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
					Message msg = handler.obtainMessage();
					msg.what = 1;
					msg.obj = "exception " + e.getMessage();
					handler.sendMessage(msg);
				}
			}

		});
	}

	/**
	 * 
	 * @author winter 要实现的接口
	 */

	public   interface OnUploadlistener {

		public  void OnSuccess(String resultData);

		public void OnError(String resultData);

	}

}
